package com.choosefine.paycenter.account.service.impl;


import com.choosefine.paycenter.account.service.AccountLockService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Comments：
 * Author：Jay Chang
 * Create Date：2017/3/29
 * Modified By：
 * Modified Date：
 * Why & What is modified：
 * Version：v1.0
 */
@Service
public class AccountLockServiceImpl implements AccountLockService{

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Value("${sys.pay.lockWaitTime}")
    private int lockWaitTime;

    /**
     * 校验账户是否被锁定
     * @param id
     * @return
     */
    public boolean isLockAccount(Long id){
        ValueOperations<String, String> stringValueOperations = redisTemplate.opsForValue();
        String lockKey=stringValueOperations.get(ACCOUNT_LOCK_PREFIX+id);
        if(StringUtils.isNotBlank(lockKey)&&"LOCKED".equals(lockKey)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 锁定账户10分钟
     * @param id
     * @return
     */
    public void lockAccount(Long id){
        ValueOperations<String, String> stringValueOperations = redisTemplate.opsForValue();
        String lockKey=ACCOUNT_LOCK_PREFIX+id;
        stringValueOperations.set(lockKey,"LOCKED");
        redisTemplate.expire(lockKey,lockWaitTime, TimeUnit.MINUTES);
    }

    /**
     * 解除锁定账户
     * @param id
     * @return
     */
    public void unlockAccount(Long id){
        String lockKey=ACCOUNT_LOCK_PREFIX+id;
        redisTemplate.delete(lockKey);
        String key = ACCOUNT_KEY_PREFIX+id;
        redisTemplate.delete(key);
    }

}
